package milk.net
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;

	public class QueueLoader extends EventDispatcher
	{
		private var queue:Vector.<ILoadItem>;
		
		private var isRuning:Boolean=false;
		
		private var currentItem:ILoadItem;
		
		public function QueueLoader()
		{
			queue=Vector.<ILoadItem>();
		}
		
		public function add(loader:ILoadItem):Boolean{
			queue.push(loader);
			
			if(currentItem==null){
				next();
			}
		}
		
		protected function next():void{
			if(queue.length==0){
				currentItem=null;
				
				this.dispatchEvent(new Event(Event.COMPLETE));
			}
			
			currentItem=queue.shift();
			currentItem.addEventListener(Event.COMPLETE,itemComHandler);
			currentItem.addEventListener(IOErrorEvent.IO_ERROR,itemComHandler);
			currentItem.addEventListener(ProgressEvent.PROGRESS,progressHandler);
			
			currentItem.load();
		}
		
		protected function progressHandler(event:ProgressEvent):void{
			
		}
		
		protected function itemComHandler(event:Event):void{
			
			var item:ILoadItem=event.currentTarget as ILoadItem;
			item.removeEventListener(Event.COMPLETE,itemComHandler);
			item.removeEventListener(IOErrorEvent.IO_ERROR,itemComHandler);
			item.removeEventListener(ProgressEvent.PROGRESS,progressHandler);
			
			
			this.next();
		}
	}
}